package com.example.graalvm21.utils.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>工具类-异常</p>
 *
 * @author wz
 *
 * @date 2025/10/27 9:56
 *
 * @version 1.0
 */
public class ExceptionUtils {

    public static final Logger log = LoggerFactory.getLogger(ExceptionUtils.class);

    public static List<Throwable> getThrowableList(Throwable throwable) {
        final List<Throwable> list = new ArrayList<>();
        while (throwable != null && !list.contains(throwable)) {
            list.add(throwable);
            throwable = throwable.getCause();
        }
        return list;
    }

    public static Throwable getRootCause(final Throwable throwable) {
        final List<Throwable> list = getThrowableList(throwable);
        return list.isEmpty() ? null : list.get(list.size() - 1);
    }

    public static String getExceptionMessage(Throwable e) {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw, true));
        return sw.toString();
    }

    public static String getRootErrorMessage(Exception e) {
        Throwable root = getRootCause(e);
        root = (root == null ? e : root);
        if (root == null) {
            return "";
        }
        String msg = root.getMessage();
        if (msg == null) {
            return "null";
        }
        return StringUtils.defaultString(msg);
    }


    public static void error(Throwable e) {
        log.error(getExceptionMessage(e));
    }

    public static void error(String format, Object arg) {
        log.error(format, arg);
    }

    public static void info(String format, Object arg) {
        log.info(format, arg);
    }
}
